#include "RTMRequest.h"
#include <openssl/md5.h>
#include <iomanip>
#include <sstream>

namespace http {
  RTMRequest::RTMRequest(const std::pair<std::string, std::string> &key, std::map<std::string, std::string> req)
    : api_key(key)
  {
    setData(req);
  }

  RTMRequest::RTMRequest(const std::pair<std::string, std::string> &key)
    : api_key(key)
  {
    std::map<std::string, std::string> req;
    setData(req);
  }

  RTMRequest& RTMRequest::setData(std::map<std::string, std::string> req) {
    std::string keys = api_key.second;
    std::map<std::string, std::string>::const_iterator reqI;

    if(req["api_key"] == "") {
      req["api_key"] = api_key.first;
    }

    reqData = "";
    for(reqI = req.begin(); reqI != req.end(); reqI++) {
      reqData.append(reqI->first).append("=").append(reqI->second).append("&");
      keys.append(reqI->first).append(reqI->second);
    }

    unsigned char * tmp_hash;
    tmp_hash = MD5((const unsigned char*) keys.c_str(), keys.length(), NULL);

    std::ostringstream os;
    for(int i=0; i < MD5_DIGEST_LENGTH; i++) {
      os << std::setfill('0') << std::setw(2) << std::hex << (int) tmp_hash[i];
    }
    reqData.append("api_sig=").append(os.str());

    return *this;
  }
}
